import React, { useEffect, useRef, useState } from 'react';
import { Chart } from '@antv/g2';
import { productsTop } from "../../../api/axios8081";
import { AxiosResponse } from 'axios';

interface ChartData {
  productName: string;
  sellSum: number;
};



const LetterFrequencyChart: React.FC = () => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [chartData, setChartData] = useState<ChartData[]>([]);
  console.log('到哪一步了')
  useEffect(() => {
    const fetchData = async () => {

      try {
        const response = await productsTop()
        console.log(response.data, 'zheli')
        if (response.data) {
          const top20Data = response.data.slice(0, 20);
          const data: ChartData[] = top20Data.map((item: { productName: string; sellSum: number; }) => ({
            productName: item.productName,
            sellSum: item.sellSum
          }));
          setChartData(data);
        } else {
          console.error('Failed to fetch product sales data:', response);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (chartRef.current) {
      const chart = new Chart({
        container: chartRef.current,
        autoFit: true,
      });

      chart.interval().data(chartData).encode('x', 'productName').encode('y', 'sellSum');
      chart.render();

      //组件卸载时销毁实例  
      return () => {
        if (chart) {
          chart.destroy();
        }
      };
    }
  }, [chartData]); // 数据变化重新渲染图表  

  return <div ref={chartRef} />;
};

export default LetterFrequencyChart;